package org.linlinjava.litemall.admin.service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import io.swagger.annotations.ApiModelProperty;
import lombok.RequiredArgsConstructor;
import org.linlinjava.litemall.admin.vo.accountbook.*;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.util.ResponseUtil.ListResponse;
import org.linlinjava.litemall.core.util.ResponseUtil.Response;
import org.linlinjava.litemall.db.beans.Constants;
import org.linlinjava.litemall.db.dao.LitemallAccountBookMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.dto.LitemallAccountBookFormDto;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.util.PageTools;
import org.springframework.stereotype.Service;



@Service
@RequiredArgsConstructor
public class AdminAccountBookService {

    private final LitemallAccountBookMapper litemallAccountBookMapper;

	private final LitemallAccountBookService litemallAccountBookService;

	private final LumiereMerchandiseImportService lumiereMerchandiseImportService;

	private final LitemallOrderService litemallOrderService;

	private final LitemallOrderFormulaMaterialService litemallOrderFormulaMaterialService;

	private final LitemallOrderGoodsService litemallOrderGoodsService;

	private final LitemallOrderPackageService litemallOrderPackageService;

	private final LitemallShopService litemallShopService;

	private final LitemallShopRegionService litemallShopRegionService;

	private final LitemallUserService litemallUserService;

	private final LitemallAdminOrderService litemallAdminOrderService;

	private final LitemallAdminOrderMerchandiseService litemallAdminOrderMerchandiseService;

	private final LitemallRechargeTransactionsService litemallRechargeTransactionsService;

	public Response shopListSummary(AccountBookShopListReqVO reqVO) {
		LambdaQueryWrapper<LitemallOrder> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
		if(reqVO.getDateTime()!=null){
			orderLambdaQueryWrapper.between(LitemallOrder::getAddTime,CollUtil.get(reqVO.getDateTime(),0),CollUtil.get(reqVO.getDateTime(),1));
		}
		List<LitemallOrder> orderList = litemallOrderService.list(orderLambdaQueryWrapper);

		// 累计总金额的变量
		//订单金额
		BigDecimal totalOrderActualPrice = BigDecimal.ZERO;
		BigDecimal totalGstPrice = BigDecimal.ZERO;
		BigDecimal totalPstPrice = BigDecimal.ZERO;
		BigDecimal totalHstPrice = BigDecimal.ZERO;

		for (LitemallOrder order : orderList) {
			totalOrderActualPrice = totalOrderActualPrice.add(order.getActualPrice());
			if(order.getGstPrice()==null)continue;
			totalGstPrice = totalGstPrice.add(order.getGstPrice());
			totalPstPrice = totalPstPrice.add(order.getPstPrice());
			totalHstPrice = totalHstPrice.add(order.getHstPrice());
		}
		//充值
		LambdaQueryWrapper<LitemallRechargeTransactions> rechargeTransactionsLambdaQueryWrapper = new LambdaQueryWrapper<>();
		if(reqVO.getDateTime()!=null){
			rechargeTransactionsLambdaQueryWrapper.between(LitemallRechargeTransactions::getAddTime,CollUtil.get(reqVO.getDateTime(),0),CollUtil.get(reqVO.getDateTime(),1));
		}
		List<LitemallRechargeTransactions> rechargeTransactionsList = litemallRechargeTransactionsService.list(rechargeTransactionsLambdaQueryWrapper);

		//总店充值
		BigDecimal totalShopRechargePrice = BigDecimal.ZERO;
		//门店现金总充值
		BigDecimal totalCashRechargePrice = BigDecimal.ZERO;

		for (LitemallRechargeTransactions item : rechargeTransactionsList) {
			BigDecimal rechargeAmount = item.getRechargeAmount();
			if (item.getPayType() != Constants.PAY_TYPE_CASH) {
				totalShopRechargePrice = totalShopRechargePrice.add(rechargeAmount);
			} else {
				totalCashRechargePrice = totalCashRechargePrice.add(rechargeAmount);
			}
		}

		//账本
		LambdaQueryWrapper<LitemallAccountBook> accountBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
		//accountBookLambdaQueryWrapper.eq(LitemallAccountBook::getRecordType,0);
		//accountBookLambdaQueryWrapper.in(shopIds.size() > 0, LitemallAccountBook::getShopId, shopIds);
		if(reqVO.getDateTime()!=null){
			accountBookLambdaQueryWrapper.between(LitemallAccountBook::getAddTime, reqVO.getDateTime().get(0), reqVO.getDateTime().get(1));
		}
		//accountBookLambdaQueryWrapper.eq(reqVO.getShopId() != null, LitemallAccountBook::getShopId, reqVO.getShopId());
		List<LitemallAccountBook> accountBookList = litemallAccountBookService.list(accountBookLambdaQueryWrapper);
		// 使用Stream API将amount属性值加起来
		//额外总收入
		BigDecimal totalIncome = accountBookList.stream()
				.filter(item->item.getRecordType()==2)
				.map(LitemallAccountBook::getAmount)
				.reduce(BigDecimal.ZERO, BigDecimal::add);
		//额外总支出
		BigDecimal totalExpenses = accountBookList.stream()
				.filter(item->item.getRecordType()==3)
				.map(LitemallAccountBook::getAmount)
				.reduce(BigDecimal.ZERO, BigDecimal::add);

		//采购总支出
		LambdaQueryWrapper<LitemallAdminOrder> adminOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
		if(reqVO.getDateTime()!=null){
			adminOrderLambdaQueryWrapper.between(LitemallAdminOrder::getAddTime, reqVO.getDateTime().get(0), reqVO.getDateTime().get(1));
		}
		List<LitemallAdminOrder> adminOrderList = litemallAdminOrderService.list(adminOrderLambdaQueryWrapper);
		//采购总支出
		BigDecimal totalAdminOrderExpenses = adminOrderList.stream()
				.map(LitemallAdminOrder::getOrderPrice)
				.reduce(BigDecimal.ZERO, BigDecimal::add);

		//excel导入原料支出
		List<LumiereMerchandiseImport> merchandiseImportList = lumiereMerchandiseImportService.list(Wrappers.lambdaQuery(LumiereMerchandiseImport.class));
		BigDecimal totalPurchasePrice = merchandiseImportList.stream()
				.map(item -> item.getPurchasePrice().multiply(BigDecimal.valueOf(item.getNumber())))
				.reduce(BigDecimal.ZERO, BigDecimal::add);

		AccountBookShopSummaryRespVO summaryResp = new AccountBookShopSummaryRespVO();
		summaryResp.setTotalOrderActualPrice(totalOrderActualPrice);
		summaryResp.setTotalShopRechargePrice(totalShopRechargePrice);
		summaryResp.setTotalCashRechargePrice(totalCashRechargePrice);
		summaryResp.setTotalImportPrice(totalPurchasePrice);
		summaryResp.setTotalIncome(totalIncome);
		summaryResp.setTotalExpenses(totalExpenses);
		summaryResp.setTotalAdminOrderExpenses(totalAdminOrderExpenses);

		summaryResp.setTotalTaxGST(totalGstPrice);
		summaryResp.setTotalTaxHST(totalHstPrice);
		summaryResp.setTotalTaxPST(totalPstPrice);




		/*// 区域
		Collection<Integer> shopIds = reqVO.getRegionId() == null ?
				CollUtil.newArrayList() : CollStreamUtil.toSet(litemallShopRegionService.queryByRegionId(reqVO.getRegionId()), LitemallShopRegion::getShopId);

		LambdaQueryWrapper<LitemallShop> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.in(shopIds.size() > 0, LitemallShop::getId, shopIds);
		queryWrapper.eq(reqVO.getShopId() != null, LitemallShop::getId, reqVO.getShopId());
		queryWrapper.orderByDesc(LitemallShop::getAddTime);

		// 获取所有门店
		List<LitemallShop> shopList = litemallShopService.selectShopPage(queryWrapper, reqVO.getPage(), reqVO.getLimit());

		// 累计总金额的变量
		BigDecimal totalActualPrice = BigDecimal.ZERO;
		BigDecimal totalGstPrice = BigDecimal.ZERO;
		BigDecimal totalPstPrice = BigDecimal.ZERO;
		BigDecimal totalHstPrice = BigDecimal.ZERO;
		BigDecimal totalExpenses = BigDecimal.ZERO;

		// 循环所有门店并累加金额
		for (LitemallShop shop : shopList) {
			// 查询该门店的所有订单
			LambdaQueryWrapper<LitemallOrder> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
			orderLambdaQueryWrapper.eq(reqVO.getPayType()!=null,LitemallOrder::getPayType,reqVO.getPayType());
			if(reqVO.getDateTime()!=null){
				orderLambdaQueryWrapper.between(LitemallOrder::getAddTime,reqVO.getDateTime().get(0),reqVO.getDateTime().get(1));
			}
			orderLambdaQueryWrapper.eq(LitemallOrder::getShopId, shop.getId());
			List<LitemallOrder> orderList = litemallOrderService.list(orderLambdaQueryWrapper);

			// 累加订单金额
			for (LitemallOrder order : orderList) {
				totalActualPrice = totalActualPrice.add(order.getActualPrice());
				totalGstPrice = totalGstPrice.add(order.getGstPrice());
				totalPstPrice = totalPstPrice.add(order.getPstPrice());
				totalHstPrice = totalHstPrice.add(order.getHstPrice());

				// 支出
				// 商品支出
				List<LitemallOrderGoods> orderGoodsList = litemallOrderGoodsService.queryByOid(order.getId());
				totalExpenses = totalExpenses.add(calculateExpensesForOrderGoodsList(orderGoodsList));

				// 套餐支出
				List<LitemallOrderPackage> orderPackageList = litemallOrderPackageService.list(Wrappers.lambdaQuery(LitemallOrderPackage.class).eq(LitemallOrderPackage::getOrderId, order.getId()));
				totalExpenses = totalExpenses.add(calculateExpensesForOrderPackageList(orderPackageList));
			}
		}


		AccountBookShopSummaryRespVO summaryResp = new AccountBookShopSummaryRespVO();
		summaryResp.setTotalIncome(totalActualPrice);
		summaryResp.setTotalTaxGST(totalGstPrice);
		summaryResp.setTotalTaxHST(totalHstPrice);
		summaryResp.setTotalTaxPST(totalPstPrice);
		summaryResp.setTotalExpenses(totalExpenses);
		summaryResp.setTotalProfit(totalActualPrice.subtract(totalExpenses));*/
		return ResponseUtil.ok(summaryResp);
	}

	public Response shopList(AccountBookShopListReqVO reqVO) {
		//区域
		Collection<Integer> shopIds = reqVO.getRegionId()==null?
				CollUtil.newArrayList() : CollStreamUtil.toSet(litemallShopRegionService.queryByRegionId(reqVO.getRegionId()),LitemallShopRegion::getShopId);

		LambdaQueryWrapper<LitemallShop> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.in(shopIds.size()>0,LitemallShop::getId,shopIds);
		queryWrapper.eq(reqVO.getShopId()!=null,LitemallShop::getId,reqVO.getShopId());
		queryWrapper.orderByDesc(LitemallShop::getAddTime);
		IPage<LitemallShop> shopList = litemallShopService.selectShopPage(queryWrapper, reqVO.getPage(), reqVO.getLimit());

		List<AccountBookShopListRespVO> respVOList = new ArrayList<>();
		for (LitemallShop shop : shopList.getRecords()) {

			LambdaQueryWrapper<LitemallOrder> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
			if(reqVO.getDateTime()!=null){
				orderLambdaQueryWrapper.between(LitemallOrder::getAddTime,CollUtil.get(reqVO.getDateTime(),0),CollUtil.get(reqVO.getDateTime(),1));
			}
			orderLambdaQueryWrapper.eq(LitemallOrder::getShopId,shop.getId());
			List<LitemallOrder> orderList = litemallOrderService.list(orderLambdaQueryWrapper);

			// 累计总金额的变量
			//订单金额
			BigDecimal orderActualPrice = BigDecimal.ZERO;
			BigDecimal gstPrice = BigDecimal.ZERO;
			BigDecimal pstPrice = BigDecimal.ZERO;
			BigDecimal hstPrice = BigDecimal.ZERO;

			for (LitemallOrder order : orderList) {
				orderActualPrice = orderActualPrice.add(order.getActualPrice());
				if(order.getGstPrice()==null)continue;
				gstPrice = gstPrice.add(order.getGstPrice());
				pstPrice = pstPrice.add(order.getPstPrice());
				hstPrice = hstPrice.add(order.getHstPrice());
			}
			//充值
			LambdaQueryWrapper<LitemallRechargeTransactions> rechargeTransactionsLambdaQueryWrapper = new LambdaQueryWrapper<>();
			if(reqVO.getDateTime()!=null){
				rechargeTransactionsLambdaQueryWrapper.between(LitemallRechargeTransactions::getAddTime,CollUtil.get(reqVO.getDateTime(),0),CollUtil.get(reqVO.getDateTime(),1));
			}
			rechargeTransactionsLambdaQueryWrapper.eq(LitemallRechargeTransactions::getShopId,shop.getId());
			rechargeTransactionsLambdaQueryWrapper.eq(LitemallRechargeTransactions::getPayType,Constants.PAY_TYPE_CASH);
			List<LitemallRechargeTransactions> rechargeTransactionsList = litemallRechargeTransactionsService.list(rechargeTransactionsLambdaQueryWrapper);

			//门店现金总充值
			BigDecimal cashRechargePrice = rechargeTransactionsList.stream()
					.map(LitemallRechargeTransactions::getRechargeAmount)
					.reduce(BigDecimal.ZERO, BigDecimal::add);

			//账本
			LambdaQueryWrapper<LitemallAccountBook> accountBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
			//accountBookLambdaQueryWrapper.eq(LitemallAccountBook::getRecordType,0);
			if(reqVO.getDateTime()!=null){
				accountBookLambdaQueryWrapper.between(LitemallAccountBook::getAddTime, reqVO.getDateTime().get(0), reqVO.getDateTime().get(1));
			}
			accountBookLambdaQueryWrapper.eq(LitemallAccountBook::getShopId, shop.getId());
			List<LitemallAccountBook> accountBookList = litemallAccountBookService.list(accountBookLambdaQueryWrapper);
			// 使用Stream API将amount属性值加起来
			//额外总收入
			BigDecimal income = accountBookList.stream()
					.filter(item->item.getRecordType()==2)
					.map(LitemallAccountBook::getAmount)
					.reduce(BigDecimal.ZERO, BigDecimal::add);
			//额外总支出
			BigDecimal expenses = accountBookList.stream()
					.filter(item->item.getRecordType()==3)
					.map(LitemallAccountBook::getAmount)
					.reduce(BigDecimal.ZERO, BigDecimal::add);

			//采购总支出
			LambdaQueryWrapper<LitemallAdminOrder> adminOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
			if(reqVO.getDateTime()!=null){
				adminOrderLambdaQueryWrapper.between(LitemallAdminOrder::getAddTime, reqVO.getDateTime().get(0), reqVO.getDateTime().get(1));
			}
			adminOrderLambdaQueryWrapper.eq(LitemallAdminOrder::getShopId,shop.getId());
			List<LitemallAdminOrder> adminOrderList = litemallAdminOrderService.list(adminOrderLambdaQueryWrapper);
			//采购总支出
			BigDecimal adminOrderExpenses = adminOrderList.stream()
					.map(LitemallAdminOrder::getOrderPrice)
					.reduce(BigDecimal.ZERO, BigDecimal::add);

			//excel导入原料支出
			List<LumiereMerchandiseImport> merchandiseImportList = lumiereMerchandiseImportService.list(Wrappers.lambdaQuery(LumiereMerchandiseImport.class)
					.eq(LumiereMerchandiseImport::getShopId, shop.getId()));
			BigDecimal totalPurchasePrice = merchandiseImportList.stream()
					.map(item -> item.getPurchasePrice().multiply(BigDecimal.valueOf(item.getNumber())))
					.reduce(BigDecimal.ZERO, BigDecimal::add);


			AccountBookShopListRespVO respVO = new AccountBookShopListRespVO();
			respVO.setShopId(shop.getId());
			respVO.setShopName(shop.getName());
			respVO.setOrderActualPrice(orderActualPrice);
			respVO.setCashRechargePrice(cashRechargePrice);
			respVO.setIncome(income);
			respVO.setExpenses(expenses);
			respVO.setAdminOrderExpenses(adminOrderExpenses);
			respVO.setImportPrice(totalPurchasePrice);
			respVO.setTaxGST(gstPrice);
			respVO.setTaxHST(hstPrice);
			respVO.setTaxPST(pstPrice);
			respVOList.add(respVO);

			/*AccountBookShopListRespVO respVO = new AccountBookShopListRespVO();
			respVO.setShopId(shop.getId());
			respVO.setShopName(shop.getName());

			LambdaQueryWrapper<LitemallOrder> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
			orderLambdaQueryWrapper.eq(reqVO.getPayType()!=null,LitemallOrder::getPayType,reqVO.getPayType());
			if(reqVO.getDateTime()!=null){
				orderLambdaQueryWrapper.between(LitemallOrder::getAddTime,reqVO.getDateTime().get(0),reqVO.getDateTime().get(1));
			}
			orderLambdaQueryWrapper.eq(LitemallOrder::getShopId, shop.getId());
			List<LitemallOrder> orderList = litemallOrderService.list(orderLambdaQueryWrapper);
			BigDecimal totalActualPrice = BigDecimal.ZERO;
			BigDecimal totalGstPrice = BigDecimal.ZERO;
			BigDecimal totalPstPrice = BigDecimal.ZERO;
			BigDecimal totalHstPrice = BigDecimal.ZERO;


			BigDecimal totalExpenses = BigDecimal.ZERO;
			for (LitemallOrder order : orderList) {
				totalActualPrice = totalActualPrice.add(order.getActualPrice());
				totalGstPrice = totalGstPrice.add(order.getGstPrice());
				totalPstPrice = totalPstPrice.add(order.getPstPrice());
				totalHstPrice = totalHstPrice.add(order.getHstPrice());

				//支出
				//商品
				List<LitemallOrderGoods> orderGoodsList = litemallOrderGoodsService.queryByOid(order.getId());
				totalExpenses = totalExpenses.add(calculateExpensesForOrderGoodsList(orderGoodsList));

				//套餐
				List<LitemallOrderPackage> orderPackageList = litemallOrderPackageService.list(Wrappers.lambdaQuery(LitemallOrderPackage.class).eq(LitemallOrderPackage::getOrderId, order.getId()));
				totalExpenses = totalExpenses.add(calculateExpensesForOrderPackageList(orderPackageList));
			}

			//账本
			LambdaQueryWrapper<LitemallAccountBook> accountBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
			accountBookLambdaQueryWrapper.eq(LitemallAccountBook::getRecordType,0);
			accountBookLambdaQueryWrapper.eq(LitemallAccountBook::getShopId,shop.getId());
			accountBookLambdaQueryWrapper.in(shopIds.size() > 0, LitemallAccountBook::getShopId, shopIds);
			if(reqVO.getDateTime()!=null){
				accountBookLambdaQueryWrapper.between(LitemallAccountBook::getAddTime, reqVO.getDateTime().get(0), reqVO.getDateTime().get(1));
			}
			accountBookLambdaQueryWrapper.eq(reqVO.getShopId() != null, LitemallAccountBook::getShopId, reqVO.getShopId());
			List<LitemallAccountBook> accountBookList = litemallAccountBookService.list(accountBookLambdaQueryWrapper);
			// 使用Stream API将amount属性值加起来
			BigDecimal totalAmount = accountBookList.stream()
					.map(LitemallAccountBook::getAmount)
					.reduce(BigDecimal.ZERO, BigDecimal::add);
			totalActualPrice = totalActualPrice.add(totalAmount);

			respVO.setIncome(totalActualPrice);
			respVO.setTaxGST(totalGstPrice);
			respVO.setTaxHST(totalHstPrice);
			respVO.setTaxPST(totalPstPrice);
			respVO.setExpenses(totalExpenses);
			respVO.setProfit(totalActualPrice.subtract(totalExpenses));
			respVOList.add(respVO);*/
		}
		return ResponseUtil.okPage(shopList,respVOList);
	}

	public Response shopListDetailsSummary(AccountBookShopListReqVO reqVO) {
		AccountBookShopListDetailsSummaryRespVO respVO = new AccountBookShopListDetailsSummaryRespVO();
		//订单
		LambdaQueryWrapper<LitemallOrder> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
		orderLambdaQueryWrapper.eq(reqVO.getPayType()!=null,LitemallOrder::getPayType,reqVO.getPayType());
		if(reqVO.getDateTime()!=null){
			orderLambdaQueryWrapper.between(LitemallOrder::getAddTime,reqVO.getDateTime().get(0),reqVO.getDateTime().get(1));
		}
		orderLambdaQueryWrapper.eq(LitemallOrder::getShopId, reqVO.getShopId());
		List<LitemallOrder> orderList = litemallOrderService.list(orderLambdaQueryWrapper);

		BigDecimal totalActualPrice = BigDecimal.ZERO;
		BigDecimal totalGstPrice = BigDecimal.ZERO;
		BigDecimal totalPstPrice = BigDecimal.ZERO;
		BigDecimal totalHstPrice = BigDecimal.ZERO;

		for (LitemallOrder order : orderList) {
			totalActualPrice = totalActualPrice.add(order.getActualPrice());
			totalGstPrice = totalGstPrice.add(order.getGstPrice());
			totalPstPrice = totalPstPrice.add(order.getPstPrice());
			totalHstPrice = totalHstPrice.add(order.getHstPrice());
		}

		//账本
		LambdaQueryWrapper<LitemallAccountBook> accountBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
		accountBookLambdaQueryWrapper.eq(LitemallAccountBook::getRecordType,0);
		if(reqVO.getDateTime()!=null){
			accountBookLambdaQueryWrapper.between(LitemallAccountBook::getAddTime, reqVO.getDateTime().get(0), reqVO.getDateTime().get(1));
		}
		accountBookLambdaQueryWrapper.eq(reqVO.getShopId() != null, LitemallAccountBook::getShopId, reqVO.getShopId());
		List<LitemallAccountBook> accountBookList = litemallAccountBookService.list(accountBookLambdaQueryWrapper);

		BigDecimal totalAmountPrice = accountBookList.stream()
				.map(LitemallAccountBook::getAmount)
				.reduce(BigDecimal.ZERO, BigDecimal::add);
		respVO.setTotalPrice(totalActualPrice);
		respVO.setTaxPST(totalPstPrice);
		respVO.setTaxHST(totalHstPrice);
		respVO.setTaxGST(totalGstPrice);
		//账本收入
		respVO.setTotalExtraIncome(totalAmountPrice);
		return ResponseUtil.ok(respVO);
	}

	public Response shopListDetails(AccountBookShopListReqVO reqVO) {
		List respVOList = new ArrayList<>();

		//订单
		LambdaQueryWrapper<LitemallOrder> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
		orderLambdaQueryWrapper.eq(reqVO.getPayType()!=null,LitemallOrder::getPayType,reqVO.getPayType());
		if(reqVO.getDateTime()!=null){
			orderLambdaQueryWrapper.between(LitemallOrder::getAddTime,reqVO.getDateTime().get(0),reqVO.getDateTime().get(1));
		}
		orderLambdaQueryWrapper.eq(LitemallOrder::getShopId, reqVO.getShopId());
		IPage<LitemallOrder> orderList = litemallOrderService.page(new Page<>(reqVO.getPage(), reqVO.getLimit()),orderLambdaQueryWrapper);

		for (LitemallOrder order : orderList.getRecords()) {
			AccountBookShopListDetailsRespVO respVO = new AccountBookShopListDetailsRespVO();
			LitemallUser user = litemallUserService.findById(order.getUserId());
			respVO.setOrderId(order.getId());
			respVO.setOrderSn(order.getOrderSn());
			respVO.setNikeName(user.getNickname());
			respVO.setUserName(user.getUsername());
			respVO.setAddTime(order.getAddTime());
			respVO.setPrice(order.getActualPrice());
			respVO.setTaxGST(order.getGstPrice());
			respVO.setTaxPST(order.getPstPrice());
			respVO.setTaxHST(order.getHstPrice());
			respVO.setPayType(order.getPayType());
			respVO.setRemark(order.getMessage());
			respVOList.add(respVO);
		}
		orderList.setRecords(respVOList);
		return ResponseUtil.okPage(orderList);
	}

	public Response shopListBookDetails(AccountBookShopListReqVO reqVO) {
		//账本
		LambdaQueryWrapper<LitemallAccountBook> accountBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
		accountBookLambdaQueryWrapper.eq(LitemallAccountBook::getRecordType,0);
		if(reqVO.getDateTime()!=null){
			accountBookLambdaQueryWrapper.between(LitemallAccountBook::getAddTime, reqVO.getDateTime().get(0), reqVO.getDateTime().get(1));
		}
		accountBookLambdaQueryWrapper.eq(reqVO.getShopId() != null, LitemallAccountBook::getShopId, reqVO.getShopId());
		List<LitemallAccountBook> accountBookList = litemallAccountBookService.list(accountBookLambdaQueryWrapper);
		List<AccountBookShopListDetailsRespVO> list = CollStreamUtil.toList(accountBookList, accountBook -> new AccountBookShopListDetailsRespVO()
				.setAddTime(accountBook.getAddTime())
				.setPrice(accountBook.getAmount())
				.setRemark(accountBook.getRemark()));
		return ResponseUtil.okList(list,accountBookList);
	}

	public Response shopListAdminOrderDetailsSummary(AccountBookShopListReqVO reqVO) {
		LambdaQueryWrapper<LitemallAdminOrder> adminOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
		adminOrderLambdaQueryWrapper.eq(LitemallAdminOrder::getShopId, reqVO.getShopId());
		adminOrderLambdaQueryWrapper.eq(StrUtil.isNotEmpty(reqVO.getOrderSn()),LitemallAdminOrder::getOrderSn, reqVO.getOrderSn());
		if(CollUtil.isNotEmpty(reqVO.getDateTime())){
			adminOrderLambdaQueryWrapper.between(LitemallAdminOrder::getAddTime, reqVO.getDateTime().get(0), reqVO.getDateTime().get(1));
		}
		List<LitemallAdminOrder> adminOrderList = litemallAdminOrderService.list(adminOrderLambdaQueryWrapper);

		Double totalGoodsNum = 0.00;
		BigDecimal totalPrice = BigDecimal.ZERO;
		for (LitemallAdminOrder adminOrder : adminOrderList) {
			List<LitemallAdminOrderMerchandise> adminOrderMerchandiseList = litemallAdminOrderMerchandiseService.querybyAdminOrderId(adminOrder.getId());
			//totalGoodsNum += adminOrderMerchandiseList.size();
			totalGoodsNum += adminOrderMerchandiseList.stream()
					.mapToDouble(LitemallAdminOrderMerchandise::getNumber)
					.sum();
			/*BigDecimal price = adminOrderList.stream()
					.map(LitemallAdminOrder::getOrderPrice)
					.reduce(BigDecimal.ZERO, BigDecimal::add);*/
			totalPrice = totalPrice.add(adminOrder.getOrderPrice());
		}
		return ResponseUtil.ok(new AccountBookAdminOrderDetailsSummaryRespVO()
				.setTotalOrderNum(adminOrderList.size()).setTotalGoodsNum(totalGoodsNum).setTotalPrice(totalPrice));
	}

	public Response shopListAdminOrderDetails(AccountBookShopListReqVO reqVO) {
		LambdaQueryWrapper<LitemallAdminOrder> adminOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
		adminOrderLambdaQueryWrapper.eq(LitemallAdminOrder::getShopId, reqVO.getShopId());
		adminOrderLambdaQueryWrapper.eq(StrUtil.isNotEmpty(reqVO.getOrderSn()),LitemallAdminOrder::getOrderSn, reqVO.getOrderSn());
		if(CollUtil.isNotEmpty(reqVO.getDateTime())){
			adminOrderLambdaQueryWrapper.between(LitemallAdminOrder::getAddTime, reqVO.getDateTime().get(0), reqVO.getDateTime().get(1));
		}
		IPage<LitemallAdminOrder> adminOrderList = litemallAdminOrderService.page(new Page<>(reqVO.getPage(), reqVO.getLimit()),adminOrderLambdaQueryWrapper);
		return ResponseUtil.okPage(adminOrderList);
	}

	public Response shopListAdminOrderDetailsV1(AccountBookShopListReqVO reqVO) {
		LambdaQueryWrapper<LitemallAdminOrder> adminOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
		adminOrderLambdaQueryWrapper.eq(LitemallAdminOrder::getShopId, reqVO.getShopId());
		adminOrderLambdaQueryWrapper.eq(StrUtil.isNotEmpty(reqVO.getOrderSn()),LitemallAdminOrder::getOrderSn, reqVO.getOrderSn());
		if(CollUtil.isNotEmpty(reqVO.getDateTime())){
			adminOrderLambdaQueryWrapper.between(LitemallAdminOrder::getAddTime, reqVO.getDateTime().get(0), reqVO.getDateTime().get(1));
		}
		IPage<LitemallAdminOrder> adminOrderList = litemallAdminOrderService.page(new Page<>(reqVO.getPage(), reqVO.getLimit()),adminOrderLambdaQueryWrapper);
		return ResponseUtil.okPage(adminOrderList);
	}

	public Response shopListOrderDetails(AccountBookShopListReqVO reqVO) {
		List<LitemallAdminOrderMerchandise> adminOrderMerchandiseList = litemallAdminOrderMerchandiseService.querybyAdminOrderId(reqVO.getOrderId());
		return ResponseUtil.ok(adminOrderMerchandiseList);
	}

	public Response shopListInputSummary(AccountBookShopListReqVO reqVO) {
		BigDecimal totalIncome = BigDecimal.ZERO;
		BigDecimal totalExpenses = BigDecimal.ZERO;
		//账本
		List<LitemallAccountBook> accountBookList = getShopListInput(reqVO);
		for (LitemallAccountBook accountBook : accountBookList) {
			if(accountBook.getRecordType() == 2){
				totalIncome = totalIncome.add(accountBook.getAmount());
			}else {
				totalExpenses = totalExpenses.add(accountBook.getAmount());
			}
		}
		return ResponseUtil.ok(new AccountBookInputSummaryRespVO()
				.setTotalIncome(totalIncome).setTotalExpenses(totalExpenses));
	}

	public Response shopListInput(AccountBookShopListReqVO reqVO) {
		//账本
		LambdaQueryWrapper<LitemallAccountBook> accountBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
		accountBookLambdaQueryWrapper.in(LitemallAccountBook::getRecordType,2,3);

		if(reqVO.getDateTime()!=null){
			accountBookLambdaQueryWrapper.between(LitemallAccountBook::getAddTime, reqVO.getDateTime().get(0), reqVO.getDateTime().get(1));
		}
		accountBookLambdaQueryWrapper.eq(reqVO.getShopId() != null, LitemallAccountBook::getShopId, reqVO.getShopId());
		IPage<LitemallAccountBook> accountBookList = litemallAccountBookMapper.selectPage(new Page<>(reqVO.getPage(), reqVO.getLimit()),accountBookLambdaQueryWrapper);
		return ResponseUtil.okPage(accountBookList);
	}

	private List<LitemallAccountBook> getShopListInput(AccountBookShopListReqVO reqVO){
		//账本
		LambdaQueryWrapper<LitemallAccountBook> accountBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
		accountBookLambdaQueryWrapper.in(LitemallAccountBook::getRecordType,2,3);

		if(reqVO.getDateTime()!=null){
			accountBookLambdaQueryWrapper.between(LitemallAccountBook::getAddTime, reqVO.getDateTime().get(0), reqVO.getDateTime().get(1));
		}
		accountBookLambdaQueryWrapper.eq(reqVO.getShopId() != null, LitemallAccountBook::getShopId, reqVO.getShopId());

		return litemallAccountBookService.list(accountBookLambdaQueryWrapper);
	}



	public BigDecimal calculateExpensesForOrderGoodsList(List<LitemallOrderGoods> orderGoodsList) {
		BigDecimal totalExpenses = BigDecimal.ZERO;
		for (LitemallOrderGoods orderGoods : orderGoodsList) {
			List<LitemallOrderFormulaMaterial> formulaMaterialList = litemallOrderFormulaMaterialService.list(Wrappers.lambdaQuery(LitemallOrderFormulaMaterial.class)
					.eq(LitemallOrderFormulaMaterial::getOrderGoodsId, orderGoods.getId()));

			for (LitemallOrderFormulaMaterial orderFormulaMaterial : formulaMaterialList) {
				BigDecimal quantity = BigDecimal.valueOf(orderFormulaMaterial.getQuantity() * orderGoods.getNumber());
				totalExpenses = totalExpenses.add(orderFormulaMaterial.getPrice().multiply(quantity));
			}
		}
		return totalExpenses;
	}


	public BigDecimal calculateExpensesForOrderPackageList(List<LitemallOrderPackage> orderPackageList) {
		BigDecimal totalExpenses = BigDecimal.ZERO;
		for (LitemallOrderPackage orderPackage : orderPackageList) {
			List<LitemallOrderGoods> orderGoodsList = litemallOrderGoodsService.getOrderGoodsByIds(orderPackage.getGoodsIds());
			totalExpenses = totalExpenses.add(calculateExpensesForOrderGoodsList(orderGoodsList));
		}
		return totalExpenses;
	}

	public Response listDetails(Integer payType,Integer shopId, Integer year, Integer month, Integer page, Integer limit){
		LocalDateTime[] monthDateTimeRange = getMonthDateTimeRange(year, month);
		//门店id统计时间内订单
		LambdaQueryWrapper<LitemallOrder> queryWrapper = new LambdaQueryWrapper();
		queryWrapper.eq(LitemallOrder::getShopId,shopId);
		queryWrapper.eq(payType!=null,LitemallOrder::getPayType,payType);
		queryWrapper.between(LitemallOrder::getAddTime,monthDateTimeRange[0],monthDateTimeRange[1]);
		queryWrapper.orderByDesc(LitemallOrder::getAddTime);

		IPage<LitemallOrder> orderList = litemallOrderService.page(new Page<>(page,limit),queryWrapper);
		return ResponseUtil.okPage(orderList);
	}
	public static LocalDateTime[] getMonthDateTimeRange(Integer year, Integer month) {
		// 获取当月第一天的00:00:00
		LocalDateTime startDateTime = LocalDate.of(year, month, 1)
				.atStartOfDay();

		// 获取当月最后一天的23:59:59
		LocalDate lastDayOfMonth = LocalDate.of(year, 1, 1)
				.plusMonths(month)
				.minusDays(1);
		LocalDateTime endDateTime = lastDayOfMonth.atTime(LocalTime.MAX);

		return new LocalDateTime[]{startDateTime, endDateTime};
	}


	public Response<AccountBookSummaryRespVO> summary(Integer shopId, Integer year, Integer month, Integer page, Integer limit) {
		List<LitemallAccountBookMonthVo> accountBookMonthList = litemallAccountBookMapper.queryMonthGroup(shopId, year, month, page, limit);
		//总收入
		BigDecimal totalIncome = BigDecimal.ZERO;
		//总支出
		BigDecimal totalExpenses = BigDecimal.ZERO;
		for (LitemallAccountBookMonthVo accountBookMonth : accountBookMonthList) {
			totalIncome = totalIncome.add(accountBookMonth.getIncome());
			totalExpenses = totalExpenses.add(accountBookMonth.getExpend());
		}
		return ResponseUtil.ok(new AccountBookSummaryRespVO()
				.setTotalIncome(totalIncome)
				.setTotalExpenses(totalExpenses)
				.setTotalProfit(totalIncome.subtract(totalExpenses)));
	}

	public Response<ListResponse<LitemallAccountBookMonthVo>> listMonthGroup(Integer shopId, Integer year, Integer month, Integer page, Integer limit) {
		List<LitemallAccountBookMonthVo> list = litemallAccountBookMapper.queryMonthGroup(shopId, year, month, page, limit);
		//统计门店erp购买货品金额
		/*list.stream().forEach(vo->{
			String dateStr = vo.getYear()+""+(vo.getMonth()<10?"0"+vo.getMonth():vo.getMonth()); // 指定年月
			LocalDate date = LocalDate.parse(dateStr + "01", DateTimeFormatter.BASIC_ISO_DATE);
			LocalDate dateFirst = date.with(TemporalAdjusters.firstDayOfMonth()); // 指定年月的第一天
			LocalDate dateEnd = date.with(TemporalAdjusters.lastDayOfMonth()); // 指定年月的最后一天

			BigDecimal priceSum = litemallAdminOrderService.selectJoinOne(BigDecimal.class, new MPJLambdaWrapper<LitemallAdminOrder>()
					.selectSum(LitemallAdminOrder::getOrderPrice)
					.leftJoin(LitemallAdminOrderMerchandise.class, LitemallAdminOrderMerchandise::getAdminOrderId, LitemallAdminOrder::getId)
					.between(LitemallAdminOrder::getAddTime,dateFirst,dateEnd)
					.eq(LitemallAdminOrder::getShopId, vo.getShopId())
			);
			vo.setExpend(priceSum==null?new BigDecimal(0.00):vo.getExpend().add(priceSum));
		});*/

		return ResponseUtil.okList(list);
	}

	/**
	 * 列表
	 *
	 * @param shopId 商店id
	 * @param year   一年
	 * @param month  月
	 * @param page   页面
	 * @param limit  限制
	 * @return {@link Response}<{@link ListResponse}<{@link LitemallAccountBook}>>
	 */
	public Response<ListResponse<LitemallAccountBook>> list(Integer shopId, Integer year, Integer month, Integer page, Integer limit) {
		LambdaQueryWrapper<LitemallAccountBook> lambdaQueryWrapper = new LambdaQueryWrapper();
		lambdaQueryWrapper.eq(LitemallAccountBook::getYear,year);
		lambdaQueryWrapper.eq(LitemallAccountBook::getMonth,month);
		lambdaQueryWrapper.eq(LitemallAccountBook::getShopId,shopId);
		lambdaQueryWrapper.orderByDesc(LitemallAccountBook::getAddTime);

		Page<LitemallAccountBook> list = litemallAccountBookMapper.selectPage(new Page<>(page, limit), lambdaQueryWrapper);
		return ResponseUtil.okPage(list);
	}



	public Response listMerchandise(Integer shopId, Integer year, Integer month, Integer page, Integer limit) {
		String dateStr = year+""+(month<10?"0"+month:month); // 指定年月
		LocalDate date = LocalDate.parse(dateStr + "01", DateTimeFormatter.BASIC_ISO_DATE);
		LocalDate dateFirst = date.with(TemporalAdjusters.firstDayOfMonth()); // 指定年月的第一天
		LocalDate dateEnd = date.with(TemporalAdjusters.lastDayOfMonth()); // 指定年月的最后一天
		IPage<LitemallAdminOrderMerchandise> litemallAdminOrderMerchandises = litemallAdminOrderMerchandiseService.selectJoinListPage(new Page<>(page,limit),LitemallAdminOrderMerchandise.class, new MPJLambdaWrapper<LitemallAdminOrderMerchandise>()
				.selectAll(LitemallAdminOrderMerchandise.class)
				.leftJoin(LitemallAdminOrder.class, LitemallAdminOrder::getId, LitemallAdminOrderMerchandise::getAdminOrderId)
				.eq(shopId!=null,LitemallAdminOrder::getShopId, shopId)
				.between(LitemallAdminOrderMerchandise::getAddTime, dateFirst, dateEnd)
		);
		return ResponseUtil.okPage(litemallAdminOrderMerchandises);
	}


	public void create(Integer shopId, LitemallAccountBookFormDto form) {
		litemallAccountBookService.create(shopId, form);
	}


	public Response importShopMerchandise( AccountBookImportReqVO reqVO) {
		IPage<LumiereMerchandiseImport> merchandiseImportList = lumiereMerchandiseImportService.page(new Page<>(reqVO.getPage(),reqVO.getLimit()),Wrappers.lambdaQuery(LumiereMerchandiseImport.class)
				.eq(LumiereMerchandiseImport::getShopId, reqVO.getShopId())
				.eq(reqVO.getId()!=null,LumiereMerchandiseImport::getId,reqVO.getId())
				.eq(StrUtil.isNotEmpty(reqVO.getClassification()),LumiereMerchandiseImport::getClassification,reqVO.getClassification())
				.eq(StrUtil.isNotEmpty(reqVO.getName()),LumiereMerchandiseImport::getName,reqVO.getName()));
		return ResponseUtil.okPage(merchandiseImportList);
	}

	public Response importShopMerchandiseSummary(AccountBookImportReqVO reqVO) {
		List<LumiereMerchandiseImport> merchandiseImportList = lumiereMerchandiseImportService.list(Wrappers.lambdaQuery(LumiereMerchandiseImport.class)
				.eq(LumiereMerchandiseImport::getShopId, reqVO.getShopId())
				.eq(reqVO.getId()!=null,LumiereMerchandiseImport::getId,reqVO.getId())
				.eq(StrUtil.isNotEmpty(reqVO.getClassification()),LumiereMerchandiseImport::getClassification,reqVO.getClassification())
				.eq(StrUtil.isNotEmpty(reqVO.getName()),LumiereMerchandiseImport::getName,reqVO.getName()));
		BigDecimal totalPurchasePrice = merchandiseImportList.stream()
				.map(item -> item.getPurchasePrice().multiply(BigDecimal.valueOf(item.getNumber())))
				.reduce(BigDecimal.ZERO, BigDecimal::add);
		Double totalCount = merchandiseImportList.stream()
				.mapToDouble(LumiereMerchandiseImport::getNumber)
				.sum();
		Map<String, Object> result = new HashMap<>();
		result.put("totalPurchasePrice", totalPurchasePrice);
		result.put("totalCount", totalCount);
		return ResponseUtil.ok(result);
	}

	public Response importShopMerchandiseListAll() {
		List<LumiereMerchandiseImport> merchandiseImportList = lumiereMerchandiseImportService.list(Wrappers.lambdaQuery(LumiereMerchandiseImport.class)
				.orderByDesc(LumiereMerchandiseImport::getAddTime));
		return ResponseUtil.ok(merchandiseImportList);
	}
}
